import { toRaw } from "vue"
import { defineStore } from "pinia"
import sysLayout_routes, { sysLayout_init_routes, sysLayout_constant_routes } from "@/router/route.config"
import { listToTree, deepClone ,sortTreeArr} from "@/common/utils"
import { authRouteMode } from "@/common/config"
import {getUserInfoApi,getSuccessStatus} from "@/api/user"
import {useUserStore} from "@/store"

const views: Record<string, any> = import.meta.glob(["/src/views/**/*.vue",])
// console.log(views)


// 根据用户具备权限的路由表生成菜单数据
function getMenu(routes: RouteItemConfig[]) {
  const menu = routes.filter(v => {
    if (!v.meta.noInMenu) {
      v.key = v.name
      if (v.children) v.children = getMenu(v.children)
      return true
    }
  })
  //  return menu.sort((a,b)=>a.meta.sortValue-b.meta.sortValue)
  return menu
}

// 采用远程路由表方案时，需要格式化一下路由配置项
function formatRoutes(routes: MenuType[]): RouteItemConfig[] {
  const metaKeys = ['title', 'icon', 'noKeepAlive', 'affix', 'noInMenu', 'hiddenMenu', 'hiddenLayout', 'sortValue','actions','link']
  const accessedRoutes: RouteItemConfig[] = []

  routes.forEach(v => {
    // meta处理
    v.meta = { title: '' }
    metaKeys.forEach(i => {
      if (Object.keys(v).includes(i)) {
        if(i=="actions")  v.meta.actionList=v.actions?.split(",")
        else v.meta[i] = v[i]
        delete v[i]
      }
    })

    // componet处理
    if (v.component) {
      if (views["/src/views" + v.component]) v.component = views["/src/views" + v.component]
      else console.log(new Error(`无法找到/src/views${v.component}对应路径的组件`))
    }
    accessedRoutes.push(v)
  })
  return listToTree<MenuType>(accessedRoutes as any, 'id', 'parentId', 'children',true, (node) => {
    // 去除多余的属性
    delete node.accessRequestList
    delete node.requestList
    delete node.pName
    delete node.pTitle
  }).children
}



export default defineStore('routes', {
  state: () => ({
    routeConfig: [] as RouteItemConfig[],      // 当前用户具备的路由配置，可以 router.addRoute(routeConfig)
    accessedRoutes: [] as RouteItemConfig[],   // 当前用户可以访问的路由项
    menu: authRouteMode == 'local' ?           // 当前用户具备的菜单
      sortTreeArr(getMenu(sysLayout_routes[0].children as RouteItemConfig[]),'meta.sortValue') :
      [] as RouteItemConfig[],
  }),
  actions: {
    setRouteConfig(config: RouteItemConfig[]) {
      this.routeConfig = config
    },
    addAccessedRoutes(accessedRoutes: RouteItemConfig[]) {
      this.accessedRoutes.push(...accessedRoutes)
    },
    setMenu(menu: any[]) {
      this.menu =menu
      console.log('menu', menu)
    },
    clearRoutes() {
      this.accessedRoutes = []
      this.routeConfig = []
      this.menu = []
    },
    async setAuth() {
      const res = await getUserInfoApi()
      if (res.code == getSuccessStatus()) {
        this.addAccessedRoutes(formatRoutes(res.data.menu))
        const user=useUserStore()
        const userInfo=deepClone(res.data,false)
        delete userInfo.menu
        delete userInfo.nameToMenuMap
        user.setUser(userInfo)
        console.log("可访问的路由",toRaw(this.accessedRoutes))
        this.addAccessedRoutes(sysLayout_constant_routes)
        this.setMenu(sortTreeArr(getMenu(deepClone(this.accessedRoutes)),'meta.sortValue')) 
        const routes = deepClone(sysLayout_init_routes)
        routes[0].children.push(...toRaw(this.accessedRoutes))
        this.setRouteConfig(routes)
        return { code: 200, accessedRoutes: routes }
      }
      return {code:res.code,message:res.message,accessedRoutes:[]}
    },
  },

})